package com.google.gwt.livinglife.server.data;

import java.util.HashSet;
import java.util.Iterator;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Extension;

import com.google.appengine.api.datastore.Link;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.livinglife.client.data.GroupIdData;
import com.google.gwt.livinglife.client.data.LivingLifeUserData;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class LivingLifeUser {
  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
  private String encodedKey;

  @Persistent
  @Extension(vendorName="datanucleus", key="gae.pk-name", value="true")
  private String id;
  
	@Persistent
	private User google_user;
	
	// This nickname is different from gmail nickname.
	// This is particular to livinglife.
	@Persistent
	String nickname;
	
	@Persistent
	private HashSet<Long> groups = new HashSet<Long>();
	
	@Persistent
	Link picture_url = new Link("");
	
	@Persistent
	String communication_email;

	public LivingLifeUser(LivingLifeUserData userData) {
		id = userData.getId();
		nickname = userData.getNickname();
		Iterator<GroupIdData> iterator = userData.getGroups().iterator();
		groups = new HashSet<Long>();
		while(iterator.hasNext()) {
			groups.add(iterator.next().getId());
		}
		if (userData.getPicture_url() != null) {
			picture_url = new Link(userData.getPicture_url());
		}
    UserService userService = UserServiceFactory.getUserService();
    google_user = userService.getCurrentUser();
    communication_email = userData.getCommunication_email();
	}

	public LivingLifeUser(User user) {
		google_user = user;
		nickname = user.getNickname();
		id = user.getUserId();
	}

	public String getEncodedKey() {
		return encodedKey;
	}

	public User getGoogle_user() {
		return google_user;
	}

	public void setGoogle_user(User googleUser) {
		google_user = googleUser;
	}

	public HashSet<Long> getGroups() {
		return groups;
	}

	public void setGroups(HashSet<Long> groups) {
		this.groups = groups;
	}

	public Link getPicture_url() {
		return picture_url;
	}

	public void setPicture_url(Link pictureUrl) {
		picture_url = pictureUrl;
	}

	public String getId() {
		return id;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getCommunication_email() {
		return communication_email;
	}

	public void setCommunication_email(String communicationEmail) {
		communication_email = communicationEmail;
	}
	
}
